﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Zwms.Client.CommonUI;
using Zwms.Data.BusinessObjects;
using Zwms.Data.CommonObject;
using System.IO;
using Zwms.Client.Helper;
using NPOI.HSSF.UserModel;
using Zwms.Client.InfoSys;

namespace Zwms.Client.OutWms
{
    public partial class OutPlanBillWnd : UserControl
    {
        #region 成员变量
        private bool _bEditable = false;
        private string _sCurrentOutPlanBillCode = "";
        #endregion

        #region 构造函数
        public OutPlanBillWnd(MainForm mainform)
        {
            InitializeComponent();
            InitBtnImage();
            InitControl();

            btnStart.Click += (a, b) =>
            {
                if (string.IsNullOrWhiteSpace(_sCurrentOutPlanBillCode))
                {
                    MessageBox.Show("请首先选择入库计划单！");
                    return;
                }


                BilOutPlanBill record = this.GetBill();
                if (record == null)
                {
                    return;
                }
                ServiceReferenceZwms.ServiceZwmsClient client
                    = new ServiceReferenceZwms.ServiceZwmsClient();
                if (record.BillStatus == "0")
                {
                    if (MessageBox.Show("进入拣货阶段出库计划单将无法修改，是否继续？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    {
                        return;
                    }

                    record.BillStatus = "1";
                    if (!client.UpdateOutPlanBill(record))
                    {
                        MessageBox.Show("出库计划单状态更新失败！");
                        return;
                    }
                }

                //首先判断状态
                switch (record.BillStatus)
                {
                    case "0":
                    case "1":
                    case "2":
                        {
                            BilOutBill queryRecord = new BilOutBill();
                            queryRecord.OBPlanCode = _sCurrentOutPlanBillCode;
                            PagerIndex pIndex = new PagerIndex(1,int.MaxValue);

                            //判断当前是否有已存在的出库单（拣货单）
                           List<BilOutBill> obBillList =   client.QueryOutBillList(queryRecord, ref pIndex).Where(c => c.BillStatus.Trim() == "0" || c.BillStatus.Trim() == "1").ToList();
                            if (obBillList.Count > 0)
                            {
                                MessageBox.Show(string.Format("当前出库计划已生成拣货单，拣货单号：{0}",obBillList[0].Id));
                                return;
                            }
                            PickBillForm window = new PickBillForm(record);
                            window.ShowDialog();
                        }
                        break;

                    case "3":
                        MessageBox.Show("该出库计划单已完成拣货");
                        break;
                    case "4":
                        MessageBox.Show("该出库计划单已撤销！");
                        break;
                }
                this.LoadBill(_sCurrentOutPlanBillCode);
            };
        }

        public OutPlanBillWnd(MainForm mainform, string sOutPlanBillCode)
        {
            InitializeComponent();
            InitBtnImage();
            InitControl();
            LoadBill(sOutPlanBillCode);
            btnStart.Click += (a, b) =>
            {
                if (string.IsNullOrWhiteSpace(_sCurrentOutPlanBillCode))
                {
                    MessageBox.Show("请首先选择入库计划单！");
                    return;
                }


                BilOutPlanBill record = this.GetBill();
                if (record == null)
                {
                    return;
                }
                ServiceReferenceZwms.ServiceZwmsClient client
                    = new ServiceReferenceZwms.ServiceZwmsClient();
                if (record.BillStatus == "0")
                {
                    if (MessageBox.Show("进入拣货阶段出库计划单将无法修改，是否继续？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    {
                        return;
                    }

                    record.BillStatus = "1";
                    if (!client.UpdateOutPlanBill(record))
                    {
                        MessageBox.Show("出库计划单状态更新失败！");
                        return;
                    }
                }

                //首先判断状态
                switch (record.BillStatus)
                {
                    case "0":
                    case "1":
                    case "2":
                        {
                            PickBillForm window = new PickBillForm(record);
                            window.ShowDialog();
                        }
                        break;

                    case "3":
                        MessageBox.Show("该出库计划单已完成拣货");
                        break;
                    case "4":
                        MessageBox.Show("该出库计划单已撤销！");
                        break;
                }
            };
        }
        #endregion

        #region 私有函数
        private void InitBtnImage()
        {
            this.btnInput.Image = global::Zwms.Client.Properties.Resources.addlist;
            this.btnNewOutPlan.Image = global::Zwms.Client.Properties.Resources.add;
            this.btnEditOutPlan.Image = global::Zwms.Client.Properties.Resources.edit;
            this.btnQueryOutPlan.Image = global::Zwms.Client.Properties.Resources.view;
            this.btnAddOutPlanDetail.Image = global::Zwms.Client.Properties.Resources.addall;
            this.btnEditOutPlanDetail.Image = global::Zwms.Client.Properties.Resources.edit2;
            this.btnDelOutPlanDetail.Image = global::Zwms.Client.Properties.Resources.remove;
            this.btnSave.Image = global::Zwms.Client.Properties.Resources.save;
            this.btnCancel.Image = global::Zwms.Client.Properties.Resources.cancel;
            this.btnOutput.Image = global::Zwms.Client.Properties.Resources.list;
            this.btnStockCheck.Image = global::Zwms.Client.Properties.Resources.refresh;

            this.btnRefresh.Image = global::Zwms.Client.Properties.Resources.refresh;
            this.btnStart.Image = global::Zwms.Client.Properties.Resources.check;
            this.btnCancelBill.Image = global::Zwms.Client.Properties.Resources.cancel2;
        }

        private BilOutPlanBill GetBill()
        {
            BilOutPlanBill record = new BilOutPlanBill();

            if (string.IsNullOrWhiteSpace(tbOutPlanBillCode.Text))
            {
                return null;
            }
            record.Id = tbOutPlanBillCode.Text;
            record.SendBillCode = tbSendBillCode.Text;
            if (cmbOBType.SelectedIndex != -1)
            {
                string sOBTypeCode = CommonHelper.GetDictKeyByValue(CommonDefine.DictOBType, cmbOBType.SelectedItem.ToString());

                if (sOBTypeCode != null)
                {
                    record.OutType = sOBTypeCode;
                }
            }

            if (!string.IsNullOrWhiteSpace(tbBillStatus.Text))
            {
                string sBillStatus = CommonHelper.GetDictKeyByValue(CommonDefine.DictOPBillStatus, tbBillStatus.Text);

                if (sBillStatus != null)
                {
                    record.BillStatus = sBillStatus;
                }
            }

            if (dpuPlanOutDate.SelectDateTime != null)
            {
                record.PlanOutDate = dpuPlanOutDate.SelectDateTime;
            }

            record.POCode = tbPOCode.Text;

            if (!string.IsNullOrWhiteSpace(tbsSender.GetTextBoxContent()))
            {
                record.SenderName = tbsSender.GetTextBoxContent();
                record.SenderCode = tbsSender.Tag.ToString();
            }
            if (!string.IsNullOrWhiteSpace(tbsReciever.GetTextBoxContent()))
            {
                record.RecieverName = tbsReciever.GetTextBoxContent();
                record.RecieverCode = tbsReciever.Tag.ToString();
            }

            return record;
        }

        private void LoadBill(string sCode)
        {
            ServiceReferenceZwms.ServiceZwmsClient client
                = new ServiceReferenceZwms.ServiceZwmsClient();

            BilOutPlanBill record = new BilOutPlanBill();
            this._sCurrentOutPlanBillCode = sCode;
            record.Id = sCode;
            record = client.QueryOutPlanBill(record);

            tbOutPlanBillCode.Text = record.Id;
            cmbOBType.SelectedIndex = cmbOBType.Items.IndexOf(CommonDefine.DictOBType[record.OutType]);
            tbSendBillCode.Text = record.SendBillCode;
            tbBillStatus.Text = CommonDefine.DictOPBillStatus[record.BillStatus];
            dpuPlanOutDate.SetDate(CommonHelper.GetDatetimeFromString(record.PlanOutDate));
            tbPOCode.Text = record.POCode;
            tbsSender.SetTextBoxContent(record.SenderName);
            tbsSender.Tag = record.SenderCode;
            tbsReciever.SetTextBoxContent(record.RecieverName);
            tbsReciever.Tag = record.RecieverCode;

            BilOutPlanBillDetail queryRecord = new BilOutPlanBillDetail();
            queryRecord.OBPlanCode = sCode;
            PagerIndex pagerIndex = new PagerIndex(1, int.MaxValue);
            IList<BilOutPlanBillDetail> outPlanBillDetailList = client.QueryOutPlanBillDetailList(queryRecord, ref pagerIndex);
            this.dgv.DataSource = null;
            if (outPlanBillDetailList.Count > 0)
            {
                this.dgv.DataSource = outPlanBillDetailList;
            }
        }

        private void InitControl()
        {
            //控制状态
            SetToolBarEditState(false);
            SetEditState(false);
        }

        private void SetToolBarEditState(bool b)
        {
            btnNewOutPlan.Enabled = !b;
            btnEditOutPlan.Enabled = !b;
            btnQueryOutPlan.Enabled = !b;
            btnAddOutPlanDetail.Enabled = b;
            btnEditOutPlanDetail.Enabled = b;
            btnDelOutPlanDetail.Enabled = b;
            btnSave.Enabled = b;
            btnCancel.Enabled = b;
        }


        public void SetEditState(bool b)
        {
            cmbOBType.Enabled = b;
            dpuPlanOutDate.SetEditState(b);
            tbSendBillCode.Enabled = b;
            tbPOCode.Enabled = b;
            tbsSender.SetEditState(b);
            tbsReciever.SetEditState(b);

            cmbOBType.BackColor = Color.White;
            dpuPlanOutDate.SetTextBGColor(Color.White);
            tbSendBillCode.BackColor = Color.White;
            tbPOCode.BackColor = Color.White;
            tbsSender.SetTextBGColor(Color.White);
            tbsReciever.SetTextBGColor(Color.White);
        }

        private void LoadOutPlanBill(string sCode)
        {
            this.LoadBill(sCode);
        }

        private void Clear()
        {
            this._bEditable = false;
            this._sCurrentOutPlanBillCode = "";
            this.tbOutPlanBillCode.Text = "";
            this.tbBillStatus.Text = "";
            this.cmbOBType.SelectedIndex = -1;
            this.dpuPlanOutDate.SetVoidDate();
            this.tbPOCode.Text = "";
            this.tbSendBillCode.Text = "";
            this.tbsSender.SetTextBoxContent("");
            this.tbsSender.Tag = "";
            this.tbsReciever.SetTextBoxContent("");
            this.tbsReciever.Tag = "";

            this.bilOutPlanBillDetailBindingSource.DataSource = null;
        }
        #endregion

        #region 控件函数
        private void btnNewOutPlan_Click(object sender, EventArgs e)
        {
            NewOutplanBillForm window = new NewOutplanBillForm();
            window.ShowDialog();
        }

        private void btnEditOutPlan_Click(object sender, EventArgs e)
        {
            if (this._sCurrentOutPlanBillCode == "")
            {
                MessageBox.Show("请首先选择出库计划单！");
                return;
            }

            if (this.GetBill().BillStatus != "0")
            {
                MessageBox.Show("只允许编辑订单状态为“制单”的计划单！");
                return;
            }

            _bEditable = true;
            SetToolBarEditState(true);
            SetEditState(true);
        }

        private void btnQueryOutPlan_Click(object sender, EventArgs e)
        {
            QueryOutPlanBillWnd uc = new QueryOutPlanBillWnd();
            ContainerForm window = new ContainerForm(uc, "选择出库计划单");
            uc.SetQueryState();
            if (window.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                if (MainForm.CurrentUser.UserRole.Trim() == "01" || MainForm.CurrentUser.UserRole.Trim() == "02")
                {
                    //无限制
                }
                else if (MainForm.CurrentUser.UserRole.Trim() == "03")
                {
                    //判断是否为该用户的入库计划单
                    if (uc.SelectedRecord.CreateUserCode != MainForm.CurrentUser.Id)
                    {
                        MessageBox.Show("对不起，您不具备该出库计划单的操作权限！");
                        return;
                    }
                }

                this._sCurrentOutPlanBillCode = uc.SelectedRecord.Id;
                LoadOutPlanBill(this._sCurrentOutPlanBillCode);
            }
        }

        private void btnAddOutPlanDetail_Click(object sender, EventArgs e)
        {
            if (this._sCurrentOutPlanBillCode == "")
            {
                MessageBox.Show("请首先选择入库计划单！");
                return;
            }


            OutPlanBillDetailForm window
                = new OutPlanBillDetailForm(EnumOpenType.New,
                    this._sCurrentOutPlanBillCode, string.Empty);
            if (window.ShowDialog() == DialogResult.OK)
            {
                LoadOutPlanBill(this._sCurrentOutPlanBillCode);
            }
        }

        private void btnEditOutPlanDetail_Click(object sender, EventArgs e)
        {
            if (dgv.CurrentCell == null)
            {
                MessageBox.Show("请首先选择入库计划明细！");
                return;
            }
             int rowIndex = dgv.CurrentCell.RowIndex;

            if (rowIndex < 0)
            {
                MessageBox.Show("请首先在列表中选中项！");
                return;
            }
            DataGridViewRow row = dgv.Rows[rowIndex];
            BilOutPlanBillDetail selectRecord = row.DataBoundItem as BilOutPlanBillDetail;
            OutPlanBillDetailForm window
                = new OutPlanBillDetailForm(EnumOpenType.Open,
                    this._sCurrentOutPlanBillCode,selectRecord.GoodsCode);
            if (window.ShowDialog() == DialogResult.OK)
            {
                LoadOutPlanBill(this._sCurrentOutPlanBillCode);
            }
        }

        private void btnDelOutPlanDetail_Click(object sender, EventArgs e)
        {
            if (dgv.CurrentCell == null)
            {
                MessageBox.Show("请首先选择入库计划明细！");
                return;
            }
            int rowIndex = dgv.CurrentCell.RowIndex;

            if (rowIndex < 0)
            {
                MessageBox.Show("请首先在列表中选中项！");
                return;
            }
            DataGridViewRow row = dgv.Rows[rowIndex];
            BilOutPlanBillDetail selectRecord = row.DataBoundItem as BilOutPlanBillDetail;

            if (MessageBox.Show("是否确认删除所选择的项？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            ServiceReferenceZwms.ServiceZwmsClient client
             = new ServiceReferenceZwms.ServiceZwmsClient();
            if (client.DeleteOutPlanBillDetail(selectRecord))
            {
                MessageBox.Show("成功！");
                LoadOutPlanBill(this._sCurrentOutPlanBillCode);
            }
            else
            {
                MessageBox.Show("失败！");
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (_bEditable == false)
            {
                return;
            }
            if (cmbOBType.SelectedIndex == 1 
                && tbsReciever.GetTextBoxContent() == "")
            {
                MessageBox.Show("货物的接收仓库！");
                cmbOBType.BackColor = Color.Yellow;
                return;
            }

            BilOutPlanBill tempRecord = this.GetBill();
            ServiceReferenceZwms.ServiceZwmsClient client
           = new ServiceReferenceZwms.ServiceZwmsClient();
            if (client.UpdateOutPlanBill(tempRecord))
            {
                SysLogWriter.WriteOptLog("保存出库单", tempRecord.Id, "改");
                MessageBox.Show("成功！");

                SetToolBarEditState(false);
                SetEditState(false);
                _bEditable = false;
            }
            else
            {
                MessageBox.Show("失败！");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            LoadOutPlanBill(this._sCurrentOutPlanBillCode);

            SetToolBarEditState(false);
            SetEditState(false);
            _bEditable = false;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (this._sCurrentOutPlanBillCode != "")
            {
                LoadOutPlanBill(this._sCurrentOutPlanBillCode);
            }
        }

        private void btnOutput_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrWhiteSpace(_sCurrentOutPlanBillCode))
            {
                MessageBox.Show("请首先选择出库计划单！");
                return;
            }

            SaveFileDialog sfDlg = new SaveFileDialog();
            sfDlg.Filter = "*.xls|*.xls";
            if (sfDlg.ShowDialog() == DialogResult.OK)
            {
                string sTemplate = System.Windows.Forms.Application.StartupPath + @"\Template\出库计划单模板.xls";
                if (!File.Exists(sTemplate))
                {
                    MessageBox.Show("模板文件不存在！");
                    return;
                }
                string sOutputDir = Path.GetDirectoryName(sfDlg.FileName);
                //打开文件
                FileStream fileTemplate = new FileStream(sTemplate, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileTemplate);
                //获取工作簿
                HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;

                //填写入库计划单基本信息
                BilOutPlanBill opBill = this.GetBill();
                sheet.CreateRow(1);
                sheet.CreateRow(2);
                sheet.CreateRow(3);
                sheet.CreateRow(4);
                sheet.CreateRow(5);
                sheet.GetRow(1).CreateCell(0);
                sheet.GetRow(1).CreateCell(1);
                sheet.GetRow(1).CreateCell(2);
                sheet.GetRow(1).CreateCell(3);
                sheet.GetRow(1).CreateCell(4);
                sheet.GetRow(2).CreateCell(0);
                sheet.GetRow(2).CreateCell(1);
                sheet.GetRow(2).CreateCell(2);
                sheet.GetRow(2).CreateCell(3);
                sheet.GetRow(2).CreateCell(4);
                sheet.GetRow(2).CreateCell(5);
                sheet.GetRow(2).CreateCell(6);
                sheet.GetRow(2).CreateCell(7);
                sheet.GetRow(2).CreateCell(8);
                sheet.GetRow(2).CreateCell(9);
                sheet.GetRow(2).CreateCell(10);
                sheet.GetRow(3).CreateCell(0);
                sheet.GetRow(3).CreateCell(1);
                sheet.GetRow(3).CreateCell(2);
                sheet.GetRow(3).CreateCell(3);
                sheet.GetRow(3).CreateCell(4);
                sheet.GetRow(3).CreateCell(5);
                sheet.GetRow(3).CreateCell(6);
                sheet.GetRow(3).CreateCell(7);
                sheet.GetRow(3).CreateCell(8);
                sheet.GetRow(3).CreateCell(9);
                sheet.GetRow(3).CreateCell(10);
                sheet.GetRow(4).CreateCell(0);
                sheet.GetRow(4).CreateCell(1);
                sheet.GetRow(4).CreateCell(2);
                sheet.GetRow(4).CreateCell(3);
                sheet.GetRow(4).CreateCell(4);
                sheet.GetRow(4).CreateCell(5);
                sheet.GetRow(4).CreateCell(6);
                sheet.GetRow(5).CreateCell(0);
                sheet.GetRow(5).CreateCell(1);
                sheet.GetRow(5).CreateCell(2);
                sheet.GetRow(5).CreateCell(3);
                sheet.GetRow(5).CreateCell(4);
                sheet.GetRow(5).CreateCell(5);
                sheet.GetRow(5).CreateCell(6);
                sheet.GetRow(5).CreateCell(7);
                sheet.GetRow(5).CreateCell(8);
                sheet.GetRow(5).CreateCell(9);
                sheet.GetRow(5).CreateCell(10);

                sheet.GetRow(1).GetCell(0).SetCellValue("客户采购订单号");
                sheet.GetRow(1).GetCell(3).SetCellValue(opBill.POCode);
                sheet.GetRow(1).GetCell(4).SetCellValue("下单日期：");

                sheet.GetRow(2).GetCell(0).SetCellValue("出库计划单号：");
                sheet.GetRow(2).GetCell(2).SetCellValue(opBill.Id);
                sheet.GetRow(2).GetCell(4).SetCellValue("计划出库日期：");
                sheet.GetRow(2).GetCell(6).SetCellValue(opBill.PlanOutDate);
                sheet.GetRow(2).GetCell(9).SetCellValue("仓管员：");
                sheet.GetRow(2).GetCell(10).SetCellValue("系统默认");

                sheet.GetRow(3).GetCell(0).SetCellValue("收货公司:");
                sheet.GetRow(3).GetCell(2).SetCellValue(opBill.RecieverName);
                sheet.GetRow(3).GetCell(4).SetCellValue("实际出库日期:");
                sheet.GetRow(3).GetCell(9).SetCellValue("审核人:");

                sheet.GetRow(4).GetCell(0).SetCellValue("收货人:");
                sheet.GetRow(4).GetCell(4).SetCellValue("发货方:");
                sheet.GetRow(4).GetCell(6).SetCellValue(opBill.SenderName);

                sheet.GetRow(5).GetCell(0).SetCellValue("收货方地址:");
                sheet.GetRow(5).GetCell(4).SetCellValue("发货单号:");
                sheet.GetRow(5).GetCell(9).SetCellValue("订单总金额：");
                sheet.GetRow(5).GetCell(10).SetCellValue("0");

                //填写入库计划货物明细信息
                int iRow = 8;
                ServiceReferenceZwms.ServiceZwmsClient client
                    = new ServiceReferenceZwms.ServiceZwmsClient();
                BilOutPlanBillDetail queryRecord = new BilOutPlanBillDetail();
                queryRecord.OBPlanCode = _sCurrentOutPlanBillCode;
                PagerIndex pagerIndex = new PagerIndex(1, int.MaxValue);
                IList<BilOutPlanBillDetail> outPlanBillDetailList = client.QueryOutPlanBillDetailList(queryRecord, ref pagerIndex);
                int i = 1;
                foreach (BilOutPlanBillDetail record in outPlanBillDetailList)
                {
                    sheet.CreateRow(iRow);
                    sheet.GetRow(iRow).CreateCell(0);
                    sheet.GetRow(iRow).CreateCell(1);
                    sheet.GetRow(iRow).CreateCell(2);
                    sheet.GetRow(iRow).CreateCell(3);
                    sheet.GetRow(iRow).CreateCell(4);
                    sheet.GetRow(iRow).CreateCell(5);
                    sheet.GetRow(iRow).CreateCell(6);
                    sheet.GetRow(iRow).CreateCell(7);
                    sheet.GetRow(iRow).CreateCell(8);
                    sheet.GetRow(iRow).CreateCell(9);
                    BaseGood querygood = new BaseGood();
                    querygood.Id = record.GoodsCode;
                    querygood = client.QueryGoods(querygood);

                    sheet.GetRow(iRow).GetCell(0).SetCellValue(i.ToString());
                    sheet.GetRow(iRow).GetCell(1).SetCellValue(record.GoodsCode.Trim());
                    sheet.GetRow(iRow).GetCell(2).SetCellValue(record.GoodsName);
                    sheet.GetRow(iRow).GetCell(3).SetCellValue(record.GoodsBarCode);
                    sheet.GetRow(iRow).GetCell(4).SetCellValue("");
                    sheet.GetRow(iRow).GetCell(5).SetCellValue(record.GoodsSpec);
                    sheet.GetRow(iRow).GetCell(6).SetCellValue(record.GoodsPackageQty.ToString());
                    sheet.GetRow(iRow).GetCell(7).SetCellValue(record.GoodsPieceQty.ToString());
                    sheet.GetRow(iRow).GetCell(8).SetCellValue(record.GoodsQty.ToString());
                    sheet.GetRow(iRow).GetCell(9).SetCellValue(querygood.RetailPrice.ToString());
                    iRow++;
                    i++;
                }
                sheet.ForceFormulaRecalculation = true;

                //保存文件
                try
                {
                    FileStream fileOutput = new FileStream(sfDlg.FileName, FileMode.Create);
                    hssfworkbook.Write(fileOutput);
                    fileOutput.Close();

                    System.Diagnostics.Process.Start(sOutputDir);
                }
                catch (IOException ex)
                {
                    MessageBox.Show("请先关闭已打开的Excel文件。");
                    return;
                }
                finally
                {
                    Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory.ToString();
                }
            }
        }

        private void tbsSender_SelectButtonClick(object sender, EventArgs e)
        {
            InfoWms.CompanyWnd uc = new InfoWms.CompanyWnd();
            CommonUI.ContainerForm window = new CommonUI.ContainerForm(uc, "选择发货方");
            uc.SetQueryState();
            if (window.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tbsSender.SetTextBoxContent(uc.SelectedRecord.CompanyName);
                tbsSender.Tag = uc.SelectedRecord.Id;
            }
        }

        private void tbsReciever_SelectButtonClick(object sender, EventArgs e)
        {
            if (cmbOBType.SelectedIndex == 0)
            {
                InfoWms.CompanyWnd uc = new InfoWms.CompanyWnd();
                CommonUI.ContainerForm window = new CommonUI.ContainerForm(uc, "选择收货方");
                uc.SetQueryState();
                if (window.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tbsReciever.SetTextBoxContent(uc.SelectedRecord.CompanyName);
                    tbsReciever.Tag = uc.SelectedRecord.Id;
                }
            }
            else if (cmbOBType.SelectedIndex == 1)
            {
                InfoWms.WarehouseWnd uc = new InfoWms.WarehouseWnd();
                CommonUI.ContainerForm window = new CommonUI.ContainerForm(uc, "选择收货仓库");
                uc.SetQueryState();
                if (window.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tbsReciever.SetTextBoxContent(uc.SelectedRecord.WarehouseName);
                    tbsReciever.Tag = uc.SelectedRecord.Id;
                }
            }
        }

        private void btnCancelBill_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_sCurrentOutPlanBillCode))
            {
                MessageBox.Show("请首先选择入库计划单！");
                return;
            }

            if (MessageBox.Show(string.Format("是否确认撤销出库计划单 {0}？", _sCurrentOutPlanBillCode.Trim()), "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            ServiceReferenceZwms.ServiceZwmsClient client
                = new ServiceReferenceZwms.ServiceZwmsClient();
            BilOutPlanBill outPlanBill = this.GetBill();
            outPlanBill.BillStatus = "4";
            if (client.UpdateOutPlanBill(outPlanBill))
            {
                _sCurrentOutPlanBillCode = string.Empty;
                this.Clear();
                MessageBox.Show("成功！");
            }
            else
            {
                MessageBox.Show("失败！");
            }
        }


        private void cmbOBType_SelectedIndexChanged(object sender, EventArgs e)
        {
            tbsReciever.SetTextBoxContent("");
            tbsReciever.Tag = "";
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            //从Excel导入出库计划单
            //1.首先读入列表
            OpenFileDialog oDlg = new OpenFileDialog();
            oDlg.Filter = "*.xls|*.xls";
            if (oDlg.ShowDialog() == DialogResult.OK)
            {
                //打开文件
                try
                {
                    FileStream fileTemplate = new FileStream(oDlg.FileName, FileMode.Open, FileAccess.Read);

                    HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileTemplate);
                    //获取工作簿
                    HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;
                    //读取入库单基本信息
                    BilOutPlanBill opBill = new BilOutPlanBill();
                    List<BilOutPlanBillDetail> opPlanBillDetailList = new List<BilOutPlanBillDetail>();
                    {
                        HSSFRow row = sheet.GetRow(1) as HSSFRow;
                        //采购单号，发货单号
                        string sPO = "";
                        if (row.GetCell(2) != null)
                        {
                            sPO = row.GetCell(2).ToString();
                        }

                        opBill.POCode = sPO;
                    }
                    {
                        HSSFRow row = sheet.GetRow(3) as HSSFRow;
                        //采购单号，发货单号
                        string sReceiverName = "";
                        if (row.GetCell(2) != null)
                        {
                            sReceiverName = row.GetCell(2).ToString();
                        }

                        opBill.RecieverName = sReceiverName;
                    }

                    {
                        HSSFRow row = sheet.GetRow(4) as HSSFRow;
                        //采购单号，发货单号
                        string sSenderName = "";
                        if (row.GetCell(6) != null)
                        {
                            sSenderName = row.GetCell(6).ToString();
                        }

                        opBill.SenderName = sSenderName;
                    }

                    {
                        HSSFRow row = sheet.GetRow(5) as HSSFRow;
                        //采购单号，发货单号
                        string sSendBillCode = "";
                        if (row.GetCell(6) != null)
                        {
                            sSendBillCode = row.GetCell(6).ToString();
                        }

                        opBill.SendBillCode = sSendBillCode;
                    }
                    {

                        int iStartRow = 8;
                        HSSFRow row = sheet.GetRow(iStartRow) as HSSFRow;
                        while (row != null && row.GetCell(0) != null && row.GetCell(0).ToString() != "")
                        {
                            string sGoodsCode = "";
                            int iPackage = 0;
                            int iPiece = 0;
                            string sRemark = "";

                            BilOutPlanBillDetail detail = new BilOutPlanBillDetail();
                            //货物编码
                            if (row.GetCell(1) != null)
                            {
                                try
                                {
                                    sGoodsCode = row.GetCell(1).ToString();
                                }
                                catch
                                {
                                    sGoodsCode = "";
                                }
                            }

                            //整箱
                            if (row.GetCell(6) != null)
                            {
                                try
                                {
                                    iPackage = int.Parse(row.GetCell(6).ToString());
                                }
                                catch
                                {
                                    iPackage = 0;
                                }
                            }

                            //零数
                            if (row.GetCell(7) != null)
                            {
                                try
                                {
                                    iPiece = int.Parse(row.GetCell(7).ToString());
                                }
                                catch
                                {
                                    iPiece = 0;
                                }
                            }

                            //零数
                            if (row.GetCell(11) != null)
                            {
                                try
                                {
                                    sRemark = row.GetCell(11).ToString();
                                }
                                catch
                                {
                                    sRemark = "";
                                }
                            }

                            detail.GoodsCode = sGoodsCode;
                            detail.GoodsPackageQty = iPackage;
                            detail.GoodsPieceQty = iPiece;
                            detail.Remark = sRemark;

                            //判断是否在入库单中存在相同的货物，如存在，则合并
                            bool b = false;
                            for (int j = 0; j < opPlanBillDetailList.Count; j++)
                            {
                                BilOutPlanBillDetail tempDetail = opPlanBillDetailList[j];
                                if (detail.GoodsCode.Trim() == tempDetail.GoodsCode.Trim())
                                {
                                    b = true;
                                    tempDetail.GoodsPackageQty += detail.GoodsPackageQty;
                                    tempDetail.GoodsPieceQty += detail.GoodsPieceQty;
                                }
                            }

                            if (!b)
                            {
                                opPlanBillDetailList.Add(detail);
                            }


                            iStartRow++;
                            row = sheet.GetRow(iStartRow) as HSSFRow;
                        }
                        if (opPlanBillDetailList.Count == 0)
                        {
                            MessageBox.Show("导入的入库计划单为空，请检查！");
                            return;
                        }
                        //判断数据的合理性
                        ServiceReferenceZwms.ServiceZwmsClient client
                            = new ServiceReferenceZwms.ServiceZwmsClient();
                        string sOPCode = client.InitOutPlanBillCode();
                        bool bHave = true;
                        List<string> unHaveGoodsList = new List<string>();
                        foreach (BilOutPlanBillDetail detail in opPlanBillDetailList)
                        {
                            BaseGood queryRecord = new BaseGood();
                            queryRecord.Id = detail.GoodsCode;
                            queryRecord = client.QueryGoods(queryRecord);
                            if (queryRecord != null)
                            {
                                detail.GoodsName = queryRecord.GoodsName;
                                detail.GoodsSpec = queryRecord.Specs;
                                detail.OBPlanCode = sOPCode;
                                detail.SingleGoodsCode = queryRecord.SingleGoodsCode;
                                detail.GoodsQty = detail.GoodsPackageQty * detail.GoodsSpec + detail.GoodsPieceQty;
                            }
                            else
                            {
                                bHave = false;
                                detail.GoodsName = "";
                                unHaveGoodsList.Add(detail.GoodsCode);
                            }
                        }
                        if (!bHave)
                        {
                            string sMessage = "";
                            for (int i = 0; i < unHaveGoodsList.Count; i++)
                            {
                                sMessage += string.Format("{0}.{1}\r\n", i + 1, unHaveGoodsList[i]);
                            }
                            MessageBox.Show(string.Format("下列商品货物列表中不存在,\r\n货物编码：\r\n{0}请检查入库计划列表！", sMessage));
                        }
                        else
                        {
                            opBill.Id = sOPCode;
                            opBill.BillStatus = "0";
                            opBill.OutType = "0";
                            opBill.IsDeactived = "0";
                            opBill.WarehouseCode = MainForm.CurrentUser.WarehouseCode;
                            opBill.WarehouseName = MainForm.CurrentUser.WarehouseName;
                            opBill.Remark = "";
                            DateTime dtNow = client.GetCurrentSystemTime();
                            opBill.CreateUserName = MainForm.CurrentUser.UserName;
                            opBill.CreateUserCode = MainForm.CurrentUser.Id;
                            opBill.CreateDate = Helper.CommonHelper.GetDateString(dtNow);
                            opBill.CreateTime = Helper.CommonHelper.GetTimeString(dtNow);

                            OPBillDetailInputForm window = new OPBillDetailInputForm(opBill,opPlanBillDetailList);
                            if (window.ShowDialog() == DialogResult.OK)
                            {
                                SysLogWriter.WriteOptLog("导入出库计划单", opBill.Id, "增");
                                if (client.AddOutPlanBill(opBill))
                                {
                                    if (client.AddOutPlanBillDetailList(opPlanBillDetailList.ToArray()))
                                    {
                                        MessageBox.Show("成功！");
                                        return;
                                    }
                                    else
                                    {
                                        MessageBox.Show("添加入库计划失败！");
                                        return;
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("添加入库计划失败！");
                                    return;
                                }
                            }
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("文件被其他程序打开，请先关闭！");
                    return;
                }
            }

        }

        private void btnStockCheck_Click(object sender, EventArgs e)
        {
            //遍历数据
            ServiceReferenceZwms.ServiceZwmsClient client
                = new ServiceReferenceZwms.ServiceZwmsClient();
            BilOutPlanBillDetail queryRecord = new BilOutPlanBillDetail();
            queryRecord.OBPlanCode = _sCurrentOutPlanBillCode;
            PagerIndex pIndex = new PagerIndex(1, int.MaxValue);
            string sRet = "";
            int i = 1;
            bool b = false;
            IList<BilOutPlanBillDetail> detailList = client.QueryOutPlanBillDetailList(queryRecord, ref pIndex);
            
            foreach (BilOutPlanBillDetail detail in detailList)
            {
                int iNeed = (detail.GoodsPackageQty * detail.GoodsSpec + detail.GoodsPieceQty)
                    - (detail.OutGoodsPackageQty * detail.GoodsSpec + detail.OutGoodsPieceQty);
                StoGoodsStock queryStock = new StoGoodsStock();
                queryStock.GoodsCode = detail.GoodsCode;
                PagerIndex pIndex1 = new PagerIndex(1, int.MaxValue);
                IList<StoGoodsStock> queryList = client.QueryGoodsStockList(queryStock, ref pIndex1);

                int iHave = queryList.Where(c=>c.WarehouseCode == MainForm.CurrentUser.WarehouseCode).Sum(c => c.GoodsTotalQty);
                if (iNeed > iHave)
                {
                    b = true;
                    sRet += string.Format("{0}.货物{1}{2}库存不足，需要{3},库存{4}.\r\n", i, detail.GoodsCode, detail.GoodsName, iNeed, iHave);
                }
            }

            if (b)
            {
                MessageBox.Show(sRet);
                return;
            }
            else
            {
                MessageBox.Show("库存满足要求！");
                return;
            }
        }
        #endregion

    }
}